#Alexander F. Gazmarariam
#afg2@princeton.edu

library(tidyverse)
library(modelsummary)
library(survey)
library(kableExtra)

source("code/fun/book_theme.r")
source("code/fun/savefig.r")
source("code/fun/coefnames4tables.r")
source("code/fun/fix_txt.r")

#load data
g <- readRDS("data/NatCAPS_20221013.rds")

#specify baseline model
f.base <- y ~ age + Female + Black + Hispanic + CollegeDegree + PartySummary + Income + employfull + rural

#specify survey weights
g.svy <- svydesign(id = ~ResponseId, weights = ~nweightWeightNEWNL33D_dupe1, data = g)

# Extent of past aid ----
aid.ols <- list()
aid.ols[["Coal"]] <- lm(update(f.base, TransitionAid_Coal_Scale ~ . + region9), g)
aid.ols[["Lumber"]] <- lm(update(f.base, TransitionAid_Lumber_Scale ~ . + region9), g)
aid.ols[["Steel"]] <- lm(update(f.base, TransitionAid_Steel_Scale ~ . + region9), g)
aid.ols[["Auto"]] <- lm(update(f.base, TransitionAid_Auto_Scale ~ . + region9), g)
aid.ols[["Tobacco"]] <- lm(update(f.base, TransitionAid_Tobacco_Scale ~ . + region9), g)
aid.ols[["Textile"]] <- lm(update(f.base, TransitionAid_Textile_Scale ~ . + region9), g)
file <- "tables/ch3/ols_pastaid.txt"
modelsummary(
  aid.ols,
  vcov = "HC2",
  stars = c("*"=.1,"**"=.05,"***"=.01),
  coef_map = coefnames,
  gof_map = c("nobs", "adj.r.squared"),
  escape=FALSE,
  output="latex"
) %>%
  cat(., file = file)
fix_txt(file)
##summary statistics
svymean(~TransitionAid_Coal_Of, g.svy)
svymean(~TransitionAid_Lumber_Of, g.svy)
svymean(~TransitionAid_Steel_Of, g.svy)
svymean(~TransitionAid_Auto_Of, g.svy)
svymean(~TransitionAid_Tobacco_Of, g.svy)
svymean(~TransitionAid_Textile_Of, g.svy)

#analyze transition success----
success.ols <- list()
success.ols[["Coal"]] <- lm(update(f.base, TransitionSuccess_Coal_Scale ~ . + region9), g)
success.ols[["Lumber"]] <- lm(update(f.base, TransitionSuccess_Lumber_Scale ~ . + region9), g)
success.ols[["Steel"]] <- lm(update(f.base, TransitionSuccess_Steel_Scale ~ . + region9), g)
success.ols[["Auto"]] <- lm(update(f.base, TransitionSuccess_Auto_Scale ~ . + region9), g)
success.ols[["Tobacco"]] <- lm(update(f.base, TransitionSuccess_Tobacco_Scale ~ . + region9), g)
success.ols[["Textile"]] <- lm(update(f.base, TransitionSuccess_Textile_Scale ~ . + region9), g)
file <- "tables/ch3/ols_pastsuccess.txt"
modelsummary(
  success.ols,
  vcov = "HC2",
  stars = c("*"=.1,"**"=.05,"***"=.01),
  coef_map = coefnames,
  gof_map = c("nobs", "adj.r.squared"),
  escape=FALSE,
  output="latex"
) %>%
  cat(., file = file)
fix_txt(file)

##summary statistics
svymean(~TransitionSuccess_Coal_Of, g.svy)
svymean(~TransitionSuccess_Lumber_Of, g.svy)
svymean(~TransitionSuccess_Steel_Of, g.svy)
svymean(~TransitionSuccess_Auto_Of, g.svy)
svymean(~TransitionSuccess_Tobacco_Of, g.svy)
svymean(~TransitionSuccess_Textile_Of, g.svy)
